﻿//Signal packer
namespace Compression.SignalCompressor
{
    using System;

    public static class SignalPacker
    {
        //Wavelet-transform
        public static int Index(int i,int n){
            if (i < 0) return -i;
            if (i >= n) return 2 * n - i - 2;
            return i;
        }

        public static void Transform(ref float[] x,ref float[] y)
        {
            int n = x.Length;
            for (int i = 0; i < n/2; i++)
            {
                y[2 * i + 1] = x[Index(2 * i + 1, n)] - (float)Math.Floor((x[Index(2 * i, n)] + x[Index(2 * i + 2, n)])/2);
                y[2 * i] = x[Index(2 * i, n)] + (float)Math.Floor((y[Index(2 * i - 1, n)] + y[Index(2 * i + 1, n)] + 2) / 4);
            }

        }

        public static void Syntes(ref float[] x, ref float[] y)
        {
            int n = x.Length;
            for (int i = 0; i < n / 2; i++)
            {
                y[2 * i] = x[Index(2 * i, n)] - (float)Math.Floor((x[Index(2 * i - 1, n)] + x[Index(2 * i + 1, n)] + 2) / 4);
            }
            for (int i = 0; i < n / 2; i++)
            {
                y[2 * i + 1] = x[Index(2 * i + 1, n)] + (float)Math.Floor((y[Index(2 * i, n)] + y[Index(2 * i + 2, n)]) / 2);
            }

        }

        public static void Reorder(ref float[] x, ref float[] y, bool inverse)
        {
            int len = x.Length / 2;
            if (inverse)
            {
                for (int i = 0; i < len; i++)
                {
                    y[i * 2] = x[i];
                    y[i * 2 + 1] = x[i + len];
                }
            }
            else
            {
                for (int i = 0; i < len; i++ )
                {
                    y[i] = x[i * 2];
                    y[i + len] = x[i * 2 + 1];
                }
            }
        }
    }
}
